import React from "react";
import { Button, Modal, Timeline, Space, Form, Input } from "antd";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import TheImage from '@/components/TheImage'
import store from "@/store/store"
import TheDialog from "@/components/TheDialog";
import RejectApplication from './components/RejectApplication'
import './style/style.scss';
import ApplyRecord from "./components/applyRecord";
import { goodsListPage, goodsClassifyList, storeList, getGoodsForceOffShelf, getGoodsBackOnShelf, getGoodsRejectApplyOnShelf } from '@/request/storeBackManage/goodsManage/goodsList'

export default class GoodsList extends React.Component {
  constructor() {
    super()
    this.state = {
      columns: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
          width: 200,
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
          width: 200,
        },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          width: 200,
          render: (text, record) => {
            return <TheImage src={record.goodsShowImages.split(',')[0]} width={80} height={80} />
          }
        },
        {
          title: "所属商家",
          dataIndex: "storeName",
          key: "storeName",
          width: 300,
        },
        {
          title: "类目",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
          width: 200,
        },
        {
          title: "状态",
          dataIndex: "goodsStatus",
          key: "goodsStatus",
          width: 200,
          render: (text) => {
            let label = ''
            switch (text) {
              case 'Y':
                label = "上架"
                break
              case 'N':
                label = '下架'
                break
              case 'P':
                label = "平台方已下架"
                break
              case 'A':
                label = '申请上架中'
                break
              default:
                label = '-'
            }
            return label
          }
        },
        {
          title: "最近操作时间",
          dataIndex: "updateTime",
          key: "updateTime",
          width: 200,
        },
        {
          title: "操作",
          fixed: 'right',
          width: 260,
          render: (text, record) => {
            return (
              <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center' }}>
                <TheButton haspermi={['goodsManage:goodsAudit:details']} onClick={() => { this.props.history.push(`/goodsManage/goodsList/goodsDetails/${record.goodsId}/${record.storeGoodsId}`) }}>商品详情</TheButton>
                {record.hasPutawayAuditRecord && <TheButton haspermi={['goodsManage:goodsAudit:record']} onClick={() => this.viewRecord(record.storeGoodsId)}>查看记录</TheButton>}
                {(record.goodsStatus === 'A' || record.goodsStatus === 'P') && <TheButton haspermi={['goodsManage:goodsAudit:recoverPutAway']} onClick={() => this.recoverPutAway(record.storeGoodsId)}>恢复上架</TheButton>}
                {record.goodsStatus === 'A' && <TheButton haspermi={['goodsManage:goodsAudit:rejectApply']} onClick={() => this.rejectApplication(record.storeGoodsId)}>驳回申请</TheButton>}
              </div>
            )
          }
        },
      ],
      newColumns: [],
      form_show: true, // 是否显示搜索
      queryForm: {},//搜索值
      searchOption: [
        {
          field: 'goodsIdOrName',
          label: '商家信息',
          placeholder: '商品ID/商品名称',
          required: false,
          type: 'Input',
          defaultValue: '',
        },
        {
          field: 'storeId',
          label: '所属商家',
          placeholder: '全部',
          type: 'Select',
          options: [],
          txt: 'storeName',
          value: 'storeId',
          api: storeList,
        },
        {
          field: 'classifyId',
          label: '所属类目',
          placeholder: '全部',
          type: 'Select',
          options: [],
          txt: 'goodsClassifyName',
          value: 'goodsClassifyId',
          api: goodsClassifyList,
          params: { level: '2' },
        },
      ],//搜索内容
      pageData: { pageNo: 1, pageSize: 10, },
      total: 1,
      isViewRecordModal: false, // 查看记录弹窗
      isForcedTakedownModal: false, //强制下架弹窗
      forcedTakedownLoading: false, //强制下架按钮loading
      isRejectApplicationModal: false, //驳回申请弹窗
      rejectApplicationLoading: false,//驳回申请按钮loading
      storeGoodsId: '',//店铺商品主键id
      backOnShelfLoading: false,//恢复上架loading
    }
  }
  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'goodsAuditList') {
      this.setState({
        queryForm,
        pageData: { pageNo, pageSize }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData(queryForm)
      })
    } else {
      this.getData()
    }
  }
  // 获取数据
  getData = (values) => {
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values },
    }, async () => {
      const params = { ...this.state.pageData, ...this.state.queryForm, goodsStatus: 'A' }
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'goodsAuditList', ...params }
      })
      let res = await goodsListPage({ ...params })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: { pageNo: res.pageNo, pageSize: res.pageSize },
          total: res.totalCount
        })
      }
    })
  }
  // 查看记录
  viewRecord = (storeGoodsId) => {
    this.setState({ isViewRecordModal: true, storeGoodsId })
  }
  // 强制下架
  forcedTakedown = (storeGoodsId) => {
    this.setState({ isForcedTakedownModal: true, storeGoodsId })
  }
  // 取消强制下架、驳回申请
  handelCancel = () => {
    this.setState({
      isForcedTakedownModal: false,
      isRejectApplicationModal: false,
    })
  }
  // 确认强制下架
  forcedTakedownFinish = async (value) => {
    this.setState({ forcedTakedownLoading: true })
    let res = await getGoodsForceOffShelf({ ...value, storeGoodsId: this.state.storeGoodsId })
    if (res.code === 0) {
      this.setState({ isForcedTakedownModal: false, forcedTakedownLoading: false })
      this.pageChange(1, 10)
    }
  }
  // 驳回申请
  rejectApplication = (storeGoodsId) => {
    this.setState({ isRejectApplicationModal: true, storeGoodsId })
  }
  // 确认驳回申请
  rejectApplicationFinish = async (value) => {
    this.setState({ rejectApplicationLoading: true })
    let res = await getGoodsRejectApplyOnShelf({ ...value, storeGoodsId: this.state.storeGoodsId })
    if (res.code === 0) {
      this.setState({ isRejectApplicationModal: false, rejectApplicationLoading: false })
      this.pageChange(1, 10)
    }
  }
  // 恢复上架
  recoverPutAway = (storeGoodsId) => {
    this.setState({ backOnShelfLoading: true })
    Modal.confirm({
      title: '提醒',
      content: '商品恢复上架后，将会展示在APP中且能被搜索到，确认恢复该商品上架？',
      okText: '恢复上架',
      cancelText: '取消',
      onOk: async () => {
        let res = await getGoodsBackOnShelf({ storeGoodsId })
        if (res.code === 0) {
          this.pageChange(1, 10)
        }
        this.setState({ backOnShelfLoading: false })
      }
    });
  }
  // 重新渲染表格
  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }
  // 搜素
  onFormSearch = (values) => {
    console.log(values, 'goodsIdOrName');
    this.setState({ pageData: { pageNo: 1, pageSize: 10 } }, () => { this.getData(values) })
  }
  // 搜索重置
  onReset = () => {
    this.setState({ queryForm: {} }, () => { this.pageChange(1, 10) })
  }
  // 切换分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };
  render() {
    let { columns, newColumns, dataSource, storeGoodsId, pageData: { pageNo, pageSize }, total, form_show, searchOption, isViewRecordModal, isRejectApplicationModal, isForcedTakedownModal, id, forcedTakedownLoading, rejectApplicationLoading } = this.state
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
        </TheTableExtend>
        <TheTable
          scroll={{ x: "960", y: '61vh' }}
          columns={newColumns}
          dataSource={dataSource}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        {/* 查看记录弹窗 */}
        <Modal
          visible={isViewRecordModal}
          title=" 申请记录"
          closable={false}
          destroyOnClose
          footer={[<Button onClick={() => this.setState({ isViewRecordModal: false })}>我知道了</Button>]} >
          <ApplyRecord storeGoodsId={storeGoodsId}></ApplyRecord>
        </Modal>
        {/* 驳回申请弹窗 */}
        <TheDialog
          title={'驳回申请'}
          footer={null}
          handleCancel={this.handelCancel}
          visible={isRejectApplicationModal}
          width='30%'
        >
          <RejectApplication id={id} handleCancel={this.handelCancel} onFinish={this.rejectApplicationFinish} loading={rejectApplicationLoading} />
        </TheDialog>
      </div>
    )
  }
}